package com.example.demo4.model

class CardMatchingGame(count: Int)  {
    var score = 0
        private set

    private val cards: MutableList<Card>
    private val cardCount: Int = count

    init {
        val deck = Deck()
        cards = mutableListOf()
        for (i in 1..count) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun cardAtIndex(index: Int): Card {
        return cards.get(index)
    }

    val MISMATCH_PENALTY = 2
    val MATCH_BONUS = 4
    val COST_TO_CHOOSE = 1

    fun reset() {
        score = 0
        val deck = Deck()
        cards.clear()
        for (i in 1..cardCount) {
            val card: Card? = deck.drawRandomCard()
            if (card != null) {
                cards.add(card)
            }
        }
    }

    fun chooseCardAtIndex(index: Int) {
        val card = cardAtIndex(index)
        if (!card.isMatched) {
            if (card.isChosen) {
                card.isChosen = false
                score += COST_TO_CHOOSE
            } else {
                val chosenCards = cards.filter { it.isChosen && !it.isMatched }
                
                when (chosenCards.size) {
                    0 -> {
                        // 第一张卡
                        score -= COST_TO_CHOOSE
                        card.isChosen = true
                    }
                    1 -> {
                        // 第二张卡
                        score -= COST_TO_CHOOSE
                        card.isChosen = true
                    }
                    2 -> {
                        // 第三张卡，进行匹配
                        score -= COST_TO_CHOOSE
                        val otherCards = chosenCards.toTypedArray()
                        val matchScore = card.match(otherCards)
                        
                        if (matchScore > 0) {
                            // 匹配成功
                            score += matchScore * MATCH_BONUS
                            otherCards[0].isMatched = true
                            otherCards[1].isMatched = true
                            card.isMatched = true
                            // 清除所有选中状态
                            otherCards[0].isChosen = false
                            otherCards[1].isChosen = false
                            card.isChosen = false
                        } else {
                            // 匹配失败
                            score -= MISMATCH_PENALTY
                            // 清除前两张的选中状态
                            otherCards[0].isChosen = false
                            otherCards[1].isChosen = false
                            // 当前卡也不选中
                            card.isChosen = false
                        }
                    }
                }
            }
        }
    }
}

